package com.lanyeo.liver.task

import android.content.Context
import android.content.res.Configuration
import android.graphics.Bitmap
import android.graphics.Point
import android.util.Log
import com.lanyeo.liver.util.TouchAction

class TaskMaking(override val context: Context) : ITask(context) {
    private var oneTimeMakeCounts = 1
    private var maxMakeTimes = 100
    private var totalMakeTimes = 0
    private var actions = mutableListOf<TouchAction>()
    override fun initTask(onTaskTouchListener: OnTaskTouchListener?, taskParams: Any): Boolean {
        oneTimeMakeCounts = (taskParams as List<Int>)[0]
        maxMakeTimes = (taskParams)[1]
        Log.d(TAG, "make count:$oneTimeMakeCounts, times:$maxMakeTimes")
        actions.clear()
        totalMakeTimes = 0
        if (oneTimeMakeCounts > 1) {
            actions.add(TouchAction(INPUT_POINT))
            if (oneTimeMakeCounts == 200) {
                // 如果是最大值直接点击最大
                actions.add(TouchAction(KEYBOARD_POINTS[MAX_CHAR]!!))
            } else {
                for (c in oneTimeMakeCounts.toString()) {
                    actions.add(TouchAction(KEYBOARD_POINTS[c]!!))
                }
            }
            actions.add(TouchAction(INPUT_OK_POINT))
        }
        actions.add(TouchAction(MAKING_POINT, 4000))
        actions.add(TouchAction(SPACE_POINT))
        return super.initTask(onTaskTouchListener, taskParams)
    }

    override fun doTask(screen: Bitmap, screenRotation: Int): Long {
        if (screenRotation != Configuration.ORIENTATION_LANDSCAPE) {
            return -1
        }
        if (totalMakeTimes >= maxMakeTimes) {
            setIsRunning(false)
            return -1
        }
        setIsRunning(true)

        touch(actions)

        totalMakeTimes++

        return nextTime(6)
    }



    override fun finishTask() {
        setIsRunning(false)
        actions.clear()
        totalMakeTimes = 0
    }

    companion object {
        const val TAG = "MakingTask"
        // 代表最大的字符
        private const val MAX_CHAR = 'b'
        private val MAKING_POINT = Point(990, 980)
        private val SPACE_POINT = Point(1155, 835)
        private val INPUT_POINT = Point(1000, 880)
        private val INPUT_OK_POINT = Point(1160, 740)
        private val KEYBOARD_POINTS = mapOf(
            '1' to Point(995, 640), '2' to Point(1105, 640), '3' to Point(1220, 640),
            '4' to Point(995, 530), '5' to Point(1105, 530), '6' to Point(1220, 530),
            '7' to Point(995, 415), '8' to Point(1105, 415), '9' to Point(1220, 415),
            'b' to Point(1330, 640), '0' to Point(1320, 415))
    }
}